<?php

namespace App\Http\Controllers\Admin\userController;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Crypt;
use DB;
class userController extends Controller
{
  public function __construct()
  {
    $this->middleware('login');
  }
	public function add()
	{
		return view('admin.user.add', ['title' => '用户添加']);
	}
	//添加用户信息代码
	public function insert(Request $request)
	{
         $this -> validate($request,[
              'uname'=>'required|min:3|max:18',
              'upwd'=>'required',
              'pepwd'=>'same:upwd',
              'tel'=>'digits:11',
              'email'=>'email',
              'uface'=>'required|image|max:2048'
         	]);
         $data = $request -> except('_token','pepwd');
         $data['upwd'] = Crypt::encryptString($data['upwd']);//对字段进行加密
         //$wzq = Crypt::decryptString($str);//对字段进行解密
         $time = Date('Y-m-d H:i:s');
         $data['regtime'] = $time;

         
         //处理头像
         if ($request -> hasFile('uface')) 
         {
            if ($request ->file('uface')-> isValid()) 
            {
                 $extension = $request -> file('uface')->extension();
    		         $filename = mt_rand(1000,9999).'.'.$extension;
    		         $dir = './uploads/avatar/';
    		         $request -> file('uface')->move($dir,$filename);
    		         $data['uface'] = '/uploads/avatar/'.$filename;
            }
         }else
         {
         	$data['uface'] = './uploads/avatar/default.jpg';
         }
         
         $res = DB::table('users')->insert($data);
         if ($res) 
         {
         	return redirect('/admin/user/index')->with(['info'=>'添加成功']);
         }else
         {
         	return back() -> with(['info'=>'添加失败']);
         }

	}
     public function change($uid)
     {
        $uid = $uid;
        return view('admin.user.change', ['title' => '修改密码','uid'=>$uid]);
     }
     public function changep(Request $request)
     {
          
        $upwd = Crypt::decryptString(session('master')->upwd);
        if ($request->input('present') != $upwd) 
        {
           return back() -> with(['info'=>'当前密码不对']);
        }

        if ($request->input('upwd') != $request->input('pepwd')) 
        {
           return back() -> with(['info'=>'两次密码输入不一致']);
        }
        $data = $request->only('upwd','uid');
        $data['upwd'] = Crypt::encryptString($data['upwd']);
       // dd($data);
       $res = DB::table('users')->where('uid',$data['uid'])->update($data);
       if ($res) 
       {
         return redirect('/admin/user/index')->with(['info'=>'密码修改成功']);
       }else
       {
         return back() -> with(['info'=>'密码修改失败']);
       }
     }
    
}
